<?php


namespace App\Exports;


use App\Models\User;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class UsersExport implements FromCollection, WithColumnWidths, WithStyles, WithCustomStartCell
{
    private $column; //总行 数

    public function collection()
    {
        $thisQuery = User::query()->with([
            "roles",
            "companies",
            "departments",
            "projects",
            "partCompanies"
        ])->orderByDesc('id');

        if (isset($args['keyword']) && !empty($args['keyword'])) {
            $keyword = $args['keyword'];
            $thisQuery->where('nickname', 'like', "%{$keyword}%")->orWhere('id', '=', $keyword)->orWhere('phone', '=', $keyword);
        }
        $list = $thisQuery->get();

        if ($list->isEmpty()) return [];

        $list = $list->toArray();

        $r_list = [];
        foreach ($list as $val) {
            $tmp = [];
            $tmp['id']           = $val['id'];
            $tmp['nickname']     = $val['nickname'];
            $tmp['phone']        = $val['phone'];
            $tmp['company']      = isset($val['companies'][0]) ? $val['companies'][0]['title'] : '未知';
            $tmp['role']         = isset($val['roles'][0]) ? $val['roles'][0]['title'] : '未知';
            $tmp['project']      = isset($val['projects'][0]) ? $val['projects'][0]['title'] : '未知';
            $tmp['part_company'] = isset($val['part_companies'][0]) ? $val['part_companies'][0]['title'] : '未知';
            $tmp['created_at']   = Carbon::parse($val['created_at'])->format('Y-m-d H:i');

            $r_list[] = $tmp;
        }
        $this->column = count($r_list) + 2;

        return collect($r_list);
    }

    /**
     * 从哪个单元格开始渲染数据，数据集合如 $list
     * @return string
     */
    public function startCell(): string
    {
        return 'A3';
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 10, 'B' => 16, 'C' => 20, 'D' => 30, 'E'=>20, 'F'=>30, 'G'=>40, 'H'=>22
        ];
    }

    /**
     * 样式设置
     * @param Worksheet $sheet
     * @throws PhpSpreadsheetException
     */
    public function styles(Worksheet $sheet)
    {
        $sheet->getDefaultRowDimension()->setRowHeight(30); //设置行高(全部行高)
        $sheet->getStyle('A1:H'.$this->column)->getFont()->setName('宋体'); //宋体
        $sheet->getStyle('A1:H'.$this->column)->getFont()->setSize(11); //大小
        $sheet->getStyle('A1:H'.$this->column)->getAlignment()->setWrapText(true); //自动换行

        $sheet->mergeCells('A1:H1');
        $sheet->setCellValue('A1', '用 户 信 息');
        $sheet->getStyle('A1')->getFont()->setSize(20); //大小
        $sheet->getStyle('A1')->getFont()->setBold(true); //粗体
        $sheet->getStyle('A2:H2')->getFont()->setBold(true); //粗体

        /**
         * 属性名设置
         */
        $sheet->setCellValue('A2', 'ID');
        $sheet->setCellValue('B2', '姓名');
        $sheet->setCellValue('C2', '手机号');
        $sheet->setCellValue('D2', '所属公司');
        $sheet->setCellValue('E2', '角色');
        $sheet->setCellValue('F2', '所属项目');
        $sheet->setCellValue('G2', '所属参建单位');
        $sheet->setCellValue('H2', '创建时间');

        /**
         * 顶部案卷目录样式设置
         */
        $sheet->getStyle('A1:H' . $this->column)->getAlignment()->setVertical('center');//垂直居中
        $sheet->getStyle('A1:H' . $this->column)->getAlignment()->setHorizontal('left');//水平居左
        $sheet->getStyle('A1')->getAlignment()->setHorizontal('center'); //水平居中

        /**
         * 设置边框
         */
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' =>  Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $sheet->getStyle('A1:H'.$this->column)->applyFromArray($styleArray);
    }

}
